package com.heima.schedule.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import com.heima.utils.common.ProtostuffUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author shitou
 * @className TaskServiceImpl
 * @description: TODO
 */
@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {

    @Resource
    private TaskinfoMapper taskinfoMapper;

    @Resource
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加延迟任务
     *
     * @param task
     * @return
     */
    @Override
    public Long addTask(Task task) {
        log.info("添加延迟任务进行中");

        // 添加任务到数据库中
        boolean flag = addTaskToDb(task);
        // 添加任务到redis中
        if (flag) {
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        // 删除数据库中任务信息 更新日志
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        // 删除redis中数据
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     * redis 中取值
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        log.info("拉取任务执行");
        Task task = null;
        try {
            String key = type + "_" + priority;
            // redis 中取出task
            String taskJson = redisService.lRightPop(ScheduleConstants.TOPIC + key);
            task = JSON.parseObject(taskJson, Task.class);
            // 更新数据库
            task = updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("拉取任务失败");
        }

        return task;
    }


    /**
     * 未来数据定时刷新
     */
    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        // 同步锁
        String token = redisService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if(StringUtils.isNotBlank(token)){
            log.info("执行了定时任务");
        // 从zset 同步到list
        // 获取所有未来数据集合的key值
        Set<String> futureKeys = redisService.scan(ScheduleConstants.FUTURE + "*");
        for (String futureKey : futureKeys) {
            //获取该组key下当前需要消费的任务数据
            Set<String> tasks = redisService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
            if (!tasks.isEmpty()) {
                //获取toipcKey
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //将这些任务数据添加到消费者队列中
                redisService.refreshWithPipeline(futureKey, topicKey, tasks);
                log.info("成功的将{}下的当前需要执行的任务数据刷新到{}}下", futureKey, topicKey);
            }
        }
        }
    }

    /**
     * 数据库数据同步到缓存
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData() {
        clearCache();
        log.info("数据库数据同步到缓存");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //查看小于未来5分钟的所有任务
        List<Taskinfo> allTasks = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime,calendar.getTime()));
        if(allTasks != null && allTasks.size() > 0){
            for (Taskinfo taskinfo : allTasks) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
    }

    private void clearCache(){
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futurekeys = redisService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topickeys = redisService.scan(ScheduleConstants.TOPIC + "*");// topic_
        redisService.delete(futurekeys);
        redisService.delete(topickeys);
    }

    /**
     * 删除redis中数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        log.info("删除redis中数据执行了");
        String key = task.getTaskType() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            redisService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            redisService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志状态
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            log.info("删除任务，更新任务日志状态执行中");
            // 删除任务
            taskinfoMapper.deleteById(taskId);
            // 更新日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            // 属性拷贝
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("任务取消失败,任务id={}", taskId);
            e.printStackTrace();
        }

        return task;
    }

    @Resource
    private RedisCacheService redisService;

    /**
     * 添加任务到redis中
     *
     * @param task
     */
    private void addTaskToCache(Task task) {
        log.info("添加任务到redis中");
        String key = task.getTaskType() + "_" + task.getPriority();
        // 如果执行时间小于等于当前时间，则存入list中
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            redisService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }
        // 如果执行时间大于当前时间，小于预设时间(当前时间+5分钟)，则存入zset中
        long fiveTime = System.currentTimeMillis() + 5 * 60 * 1000;
        if (task.getExecuteTime() > System.currentTimeMillis() && task.getExecuteTime() < fiveTime) {
            redisService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }


    }

    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = false;
        try {
            log.info("添加任务到数据库中");
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);

            // 添加数据
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }


}
